import React, { useEffect, useState } from 'react'
import { Input, Button, Table, Modal, Row, Col, DatePicker, Divider } from 'antd'
import { connect } from 'umi'

const CreateUpdateForm = (props) => {

  const [loading, setLoading] = useState(false)
  const { onSubmit, onCancel, visible, operationType, current } = props
  const [data, setData] = useState({})
  const [cacheOriginData, setCacheOriginData] = useState({})
  const [clickedCancel, setClickedCancel] = useState(false)

  useEffect(() => {
    if (current && visible) {
      setData(
        current.map((item, index) => {
          return { key: 'had' + index, ...item }
        })
      )
    }
  }, [visible])

  const onFormCancel = () => {
    onCancel()
  }

  const handleSubmit = async () => {
    onSubmit(data)
  }

  const columns = [
    {
      title: '姓名',
      fixed: 'left',
      // width: 100,
      align: 'center',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '参保地',
      // width: 150,
      fixed: 'left',
      align: 'center',
      dataIndex: 'cityName',
    },
    {
      title: '参保单位',
      align: 'center',
      fixed: 'left',
      // width: 200,
      dataIndex: 'unitName',
    },
    {
      title: '养老保险',
      // width: 400,
      dataIndex: 'endowmentInsurancePerson',
      children: [
        {
          title: '个人',
          // width: 200,
          align: 'center',
          dataIndex: 'endowmentInsurancePerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'endowmentInsurancePerson', record.key)}/>
              )
            }
            return text
          },
        },
        {
          title: '公司',
          // width: 200,
          align: 'center',
          dataIndex: 'endowmentInsuranceOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'endowmentInsuranceOrg', record.key)}/>
              )
            }
            return text
          },
        }
      ]
    },
    {
      title: '工伤保险',
      // width: 400,
      children: [
        {
          title: '个人',
          // width: 200,
          align: 'center',
          dataIndex: 'injuryInsurancePerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'injuryInsurancePerson', record.key)}/>
              )
            }
            return text
          },
        },
        {
          title: '公司',
          // width: 200,
          align: 'center',
          dataIndex: 'injuryInsuranceOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'injuryInsuranceOrg', record.key)}/>
              )
            }
            return text
          },
        }
      ]
    },
    {
      title: '重大医疗',
      // width: 400,
      children: [
        {
          title: '个人',
          align: 'center',
          // width: 200,
          dataIndex: 'largerMedicalPerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'largerMedicalPerson', record.key)}/>
              )
            }
            return text
          },
        },
        {
          title: '公司',
          align: 'center',
          // width: 200,
          dataIndex: 'largerMedicalOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'largerMedicalOrg', record.key)}/>
              )
            }
            return text
          },
        }
      ]
    },
    {
      title: '医疗保险',
      // width: 400,
      children: [
        {
          title: '个人',
          align: 'center',
          // width: 200,
          dataIndex: 'medicalInsurancePerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'medicalInsurancePerson', record.key)}/>
              )
            }
            return text
          },
        },
        {
          title: '公司',
          align: 'center',
          // width: 200,
          dataIndex: 'medicalInsuranceOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'medicalInsuranceOrg', record.key)}/>
              )
            }
            return text
          },
        }
      ]
    },
    {
      title: '失业保险',
      // width: 400,
      children: [
        {
          title: '个人',
          align: 'center',
          // width: 200,
          dataIndex: 'unemploymentInsurancePerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'unemploymentInsurancePerson', record.key)}/>
              )
            }
            return text
          },
        },
        {
          title: '公司',
          align: 'center',
          // width: 200,
          dataIndex: 'unemploymentInsuranceOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'unemploymentInsuranceOrg', record.key)}/>
              )
            }
            return text
          },
        }
      ]
    },
    {
      title: '残疾保障金',
      children: [
        {
          title: '个人',
          dataIndex: 'disabledEmploymentPerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'disabledEmploymentPerson', record.key)}/>
              )
            }
            return text
          },
        },
        {
          title: '公司',
          dataIndex: 'disabledEmploymentOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'disabledEmploymentOrg', record.key)}/>
              )
            }
            return text
          },
        }
      ]
    },
    {
      title: '生育保险',
      children: [
        {
          title: '个人',
          dataIndex: 'maternityInsurancePerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'maternityInsurancePerson', record.key)}/>
              )
            }
            return text
          },
        },
        {
          title: '公司',
          dataIndex: 'maternityInsuranceOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text === '-' ? '' : text}
                       onChange={(e) => handleFieldChange(e, 'maternityInsuranceOrg', record.key)}/>
              )
            }
            return text
          },
        }
      ]
    },
    /*{
      title: '合计',
      fixed: 'right',
      width: 200,
      children: [
        {
          title: '个人',
          fixed: 'right',
          dataIndex: 'personCostTotal',
          hideInSearch: true,
          width: 100
        },
        {
          title: '公司',
          fixed: 'right',
          dataIndex: 'orgCostTotal',
          hideInSearch: true,
          width: 100
        },
      ]
    },*/
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: '150px',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
          </span>
        )
      },
    },
  ]

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0]

  const toggleEditable = (e, key, record) => {
    e.preventDefault()
    const newData = data?.map((item) => ({ ...item }))
    const target = getRowByKey(key, newData)
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = { ...target }
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable
      setData(newData)
    }
  }

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data]
    const target = getRowByKey(key, newData)
    if (target) {
      target[fieldName] = e.target ? e.target.value : e
      setData(newData)
    }
  }

  const updateRow = (e, rowKey) => {
    e.persist()
    if (clickedCancel) {
      setClickedCancel(false)
      return
    }
    toggleEditable(e, rowKey)
  }

  const cancel = (e, key) => {
    setClickedCancel(true)
    e.preventDefault()
    const newData = [...data] // 编辑前的原始数据
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = { ...item, ...cacheOriginData[key], editable: false }
          delete cacheOriginData[key]
          setCacheOriginData(cacheOriginData)
          return originItem
        }
      }
      return item
    })
    setData(cacheData)
    setClickedCancel(false)
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        {/*<Button type="primary" onClick={() => exportExcel()}>导出</Button>*/}
        <Button type="primary" onClick={() => handleSubmit()}>确认修改</Button>
      </>
    )
  }

  return (
    <Modal
      width={'90%'}
      destroyOnClose
      title="修改预览"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      maskClosable={false}
    >

      <Table
        loading={loading}
        bordered
        pagination={false}
        rowKey="recordId"
        columns={columns}
        dataSource={data}
        scroll={{ x: 2000 }}
      />

    </Modal>
  )
}

export default connect(({ user, personnel, global }) => ({
  global
}))(CreateUpdateForm)
